package com.my.study.aop.aspect;

import com.my.study.aop.anntation.FileTypeCheck;
import com.my.study.enums.BusinessExceptionEnum;
import com.my.study.enums.CheckTypeEnum;
import com.my.study.exception.BusinessException;
import com.my.study.handler.FileCheckHandler;
import com.my.study.utils.ExcelReadUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Component
@Aspect
@Slf4j
@Order(1)
public class FileCheckAspect {

    /**
     * * com.hkl.modules.*.controller..*(..))
     * 切面
     * @param joinPoint
     * @param fileTypeCheck
     */
    @Before("@annotation(fileTypeCheck)")
    public void before(JoinPoint joinPoint, FileTypeCheck fileTypeCheck) {
        try {
            // 获取切面信息
            int fileNum = fileTypeCheck.fileNum();
            long fileSize = fileTypeCheck.size();
            String[] suffix = fileTypeCheck.suffix();
            CheckTypeEnum[] checkTypeEnums = fileTypeCheck.checkTypeEnum();
            // 获取请求对象
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();
            MultipartResolver resolver = new StandardServletMultipartResolver();
            MultipartHttpServletRequest mRequest = resolver.resolveMultipart(request);
            Map<String, MultipartFile> fileMap = mRequest.getFileMap();
            // 文件数量校验
            FileCheckHandler.checkFileNum(fileMap, checkTypeEnums, fileNum);
            // 其他校验
            fileMap.forEach((key, val) -> {
                FileCheckHandler.checkFileCommon(checkTypeEnums, val, suffix, fileSize);
            });
        } catch (Exception exception) {
            ExcelReadUtil.handlerException(exception);
            throw BusinessException.fail(BusinessExceptionEnum.FAIL.code, "文件校验异常");
        }
    }
}
